package cn.dyw.shop.mapping;

import cn.dyw.shop.json.Json;
import cn.dyw.shop.model.User;
import cn.dyw.shop.service.UserService;
import cn.dyw.shop.utils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;

/**
 * @author: dyw770
 * @date: 2018/5/6
 */
@Controller
@RequestMapping("/user")
public class UserMapping extends BaseMapping<User> {

    @Autowired
    protected void setBaseService(UserService userService) {
        this.baseService = userService;
    }

    /**
     * 登录
     * @param user
     * @param session
     * @return
     */
    @ResponseBody
    @RequestMapping("/login")
    public Json login(User user, HttpSession session) {
        User login = ((UserService) baseService).login(user);
        if (login != null) {
            session.setAttribute("user", login);
            return Json.factory(login, true, 1001, "success");
        } else {
            return Json.factory(null, false, 1002, "fal");
        }
    }

    /**
     * 注册
     * @param user
     * @return
     */
    @ResponseBody
    @RequestMapping("/register")
    public Json register(User user) {
        baseService.save(user);
        return Json.factory(user, true, 1001, "success");
    }

    /**
     * 资料
     * @param session
     * @return
     */
    @ResponseBody
    @RequestMapping("/data")
    public Json register(HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return Json.factory(user, false, 1002, "请先登录");
        }
        return Json.factory(user, true, 1001, "success");
    }

    @ResponseBody
    @RequestMapping("/update")
    public Json update(HttpSession session, User user) {
        User user1 = (User) session.getAttribute("user");
        BeanUtils.copyNotNullProperties(user, user1);
        save(user1);
        session.setAttribute("user", user1);
        return Json.factory(user1, true, 1001, "success");
    }
}
